import { queryVehicleDetail } from '../../services/vehicle'
import { inspectorSaveOrder } from '../../services/order'
import { queryInstDetailInfo } from '../../services/project'
import { updateInstInfo } from '../../services/inspect'
import { queryUrlsBySpaceId, queryRealData } from '../../services/inspect'
import dayjs from 'dayjs'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId:"",
    vehicleId:"",
    instId:"",
    spaceId:"",
    vehicleInfo:{},
    showPopup: false,
    pickColumns:['合格', '不合格'],
    insulationList:[
      {
        type:'DC',
        title:"直流充电口",
        infoList:[
          {
            tag:1,
            name:'绝缘电阻',
            outputValue:"1000V",
            valueUrl:'fc_insulation_resist',
            checkUrl:'fcir_conclusion',
            measuredValue:"",
            checkRes:""
          },
          {
            tag:2,
            name:'直流耐压',
            outputValue:"2100kV",
            valueUrl:'voltage_fcdc',
            checkUrl:'fcdc_conclusion',
            measuredValue:"",
            checkRes:""
          },
          {
            tag:3,
            name:'交流耐压',
            outputValue:"1500kV",
            valueUrl:'voltage_fcac',
            checkUrl:'fcac_conclusion',
            measuredValue:"",
            checkRes:""
          },
        ]
      },
      {
        type:'AC',
        title:"交流充电口",
        infoList:[
          {
            tag:1,
            name:'绝缘电阻',
            outputValue:"1000V",
            valueUrl:'insulation_resist',
            checkUrl:'ir_conclusion',
            measuredValue:"",
            checkRes:""
          },
          {
            tag:2,
            name:'直流耐压',
            outputValue:"2100kV",
            valueUrl:'voltage_dc',
            checkUrl:'dc_conclusion',
            measuredValue:"",
            checkRes:""
          },
          {
            tag:3,
            name:'交流耐压',
            outputValue:"1500kV",
            valueUrl:'voltage_ac',
            checkUrl:'ac_conclusion',
            measuredValue:"",
            checkRes:""
          },
        ]
      },
    ],
    currentType:"",
    currentTag:"",
    instInfo:{},
    showInstDate: true,
    urlsList:[],
    allInfoUrlList:['voltage_ac', 'ac_conclusion', 'voltage_dc', 'dc_conclusion', 'insulation_resist', 'ir_conclusion', 'voltage_fcac', 'fcac_conclusion', 'voltage_fcdc', 'fcdc_conclusion', 'fc_insulation_resist', 'fcir_conclusion', 'all_conclusion'],
    AcTypeList:['voltage_ac', 'ac_conclusion', 'voltage_dc', 'dc_conclusion', 'insulation_resist', 'ir_conclusion'],
    DcTypeList:['voltage_fcac', 'fcac_conclusion', 'voltage_fcdc', 'fcdc_conclusion', 'fc_insulation_resist', 'fcir_conclusion'],
    dcInfo:[],
    acInfo:[],
    timer: null,
    weatherInfo:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options){
      return
    }
    let orderId = options.orderId
    let vehicleId = options.vehicleId
    let instId = options.instId
    let spaceId = options.spaceId
    this.setData({
      orderId,
      vehicleId,
      instId,
      spaceId
    })
    if(vehicleId){
      this.getVehicleDetail(vehicleId)
    }
    if(instId){
      this.getInstDetailInfo(instId)
    }
    if(spaceId){
      this.getInfoListBySpaceId(spaceId)
    }
  },

  onHide(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  onUnload(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  async getVehicleDetail(vehicleId){
    let res = await queryVehicleDetail(vehicleId)
    if(res.code === 200){
      let vehicleInfo = res.data
      this.setData({
        vehicleInfo
      })      
    }
  },

  async getInstDetailInfo(instId){
    let res = await queryInstDetailInfo(instId)
    console.log("inst>>>detail>>>", res)
    if(res.code === 200){
      let instInfo = res.data
      let resJson = res.data.itemJson
      if(resJson){
        let insulationList = typeof resJson == 'string' ? JSON.parse(resJson) : resJson 
        this.setData({
          insulationList,
          instInfo
        })
      }
    }
  },

  handleSelect(event){
    let currentType = event.currentTarget.dataset.type 
    let currentTag = event.currentTarget.dataset.tag
    this.setData({
      showPopup: true,
      currentType,
      currentTag
    })
    this.handleSaveEndTime()
  },

  async handleSaveEndTime(){
    this.setData({
      [`instInfo.detectEndTime`]: dayjs().format("YYYY-MM-DD HH:mm:ss")
    })

    let data = {
      id: this.data.instId,
      detectEndTime: this.data.instInfo.detectEndTime,
    }
    let saveRes = await updateInstInfo(data)
  },


  checkResIsOk(){
    let res = true
    let resList = this.data.insulationList
    for(let item of resList){
      item.infoList.forEach( iten => {
        if(!iten.measuredValue || !iten.checkRes){
          res = false
        }
      })
    }
    return res
  },

  async confirmInfo(){
    let insulationList = this.data.insulationList
    let itemJson = JSON.stringify(insulationList)
    let weatherInfo = wx.getStorageSync('weatherInfo') || ''
    let tempList = []
    let checkIsOk = this.checkResIsOk()
    console.log("checkIsOk>>>", checkIsOk)
    let channelInfo = {
      id: this.data.instId,
      itemJson: itemJson,
      desc: JSON.stringify(weatherInfo),
      confirmInfo: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      detectEndTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
      // [`instInfo.detectEndTime`]: dayjs().format("YYYY-MM-DD HH:mm:ss")
    }
    if(checkIsOk){
      channelInfo.status = 3
    }
    tempList.push(channelInfo)

    let res = await inspectorSaveOrder(tempList)
    if(res.code === 200){
      wx.reLaunch({
        url: `/pages/order-handle/order-handle?id=${this.data.orderId}&vehicleId=${this.data.vehicleId}`,
      })
    }
  },

  onClose(){},

  onCancel(){
    this.setData({
      currentType:"",
      currentTag:"",
      showPopup:false
    })
  },

  onConfirm(confirmRes){
    let checkRes = confirmRes.detail.value
    let currentType = this.data.currentType
    let currentTag = this.data.currentTag
    let tempList = this.data.insulationList
    let currentIndex = tempList.findIndex(item => item.type == currentType)
    let currentItem = tempList.find(item => item.type == currentType)
    currentItem.infoList.forEach(item => {
      if(item.tag == currentTag){
        item.checkRes = checkRes
      }
    })

    this.setData({
      showPopup:false,
      [`insulationList[${currentIndex}]`]:currentItem
    })
  },

  handleInput(event){
    let currentType = event.currentTarget.dataset.type 
    let currentTag = event.currentTarget.dataset.tag
    let val = event.detail.value
    let tempList = this.data.insulationList
    let currentIndex = tempList.findIndex(item => item.type == currentType)
    let currentItem = tempList.find(item => item.type == currentType)
    currentItem.infoList.forEach(item => {
      if(item.tag == currentTag){
        item.measuredValue = val
      }
    })

    this.setData({
      [`insulationList[${currentIndex}]`]:currentItem
    })
    this.handleSaveEndTime()
  },

  onChangePicker(){},

  // 获取实时数据
  async getInfoListBySpaceId(spaceId){
    let res = await queryUrlsBySpaceId({ spaceId })
    if(res.code === 200){
      let urlsList = res.rows
      this.getUrlIds(this.data.allInfoUrlList, urlsList)
      this.setData({
        urlsList
      })
    }
  },

  getUrlIds(urls, urlsList){
    let ids = []
    urls.forEach(item => {
      let searchItem = urlsList.find( iten => iten.url.toUpperCase() == item.toUpperCase())
      ids.push(searchItem.id)
    })
    
    this.getRealData(ids)
    const _this = this
    let timer = setInterval(function(){
      _this.getRealData(ids)
    }, 3000)
    this.setData({
      timer
    })
  },

  getUrlInfos(urls, urlsList){
    let urlInfos = []
    urls.forEach(item => {
      let searchItem = urlsList.find( iten => iten.url.toUpperCase() == item.toUpperCase())
      urlInfos.push(searchItem)
    })
    return urlInfos
  },

  async getRealData(ids){
    let allInfoList = []
    let orderId = this.data.orderId
    let res = await queryRealData(ids)
    if(res.code == 200){
      allInfoList = res.data
      if(allInfoList[0] && allInfoList[0]['timestamp']){
        let nowDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
        let lastInspectTime = dayjs(allInfoList[0]['timestamp']).format('YYYY-MM-DD HH:mm:ss')
        let difftime = dayjs(nowDate).diff(lastInspectTime)
        // let hasData = this.data.hasData
        if(difftime > 300000){
          console.log("超过五分钟了",difftime)
          // wx.showLoading({
          //   title: '暂无数据...',
          // })
          return
        }
      }
      this.setInfoData(allInfoList)

      // let dcInfo = this.getUrlInfos(this.data.DcTypeList, allInfoList)
      // let acInfo = this.getUrlInfos(this.data.AcTypeList, allInfoList)
      // this.setData({
      //   dcInfo,
      //   acInfo
      // })
    }
  },

  getValDetailInfo(urlStr, infoList){
    let valueDetail = ""
    infoList.forEach(item => {
      if(item.url == urlStr){
        valueDetail = item.value
      }
    })
    return valueDetail
  },

  getCheckDetailInfo(urlStr, infoList){
    let valueDetail = ""
    infoList.forEach(item => {
      if(item.url == urlStr){
        if(item.value == '1'){
          valueDetail = '合格'
        } else {
          valueDetail = '不合格'
        }
      }
    })
    return valueDetail
  },

  setInfoData(allInfoList){
    let insulationList = [
      {
        type:'DC',
        title:"直流充电口",
        infoList:[
          {
            tag:1,
            name:'绝缘电阻',
            outputValue:"1000V",
            valueUrl:'fc_insulation_resist',
            checkUrl:'fcir_conclusion',
            measuredValue: this.getValDetailInfo('fc_insulation_resist', allInfoList),
            checkRes: this.getCheckDetailInfo('fcir_conclusion', allInfoList)
          },
          {
            tag:2,
            name:'直流耐压',
            outputValue:"2100kV",
            valueUrl:'voltage_fcdc',
            checkUrl:'fcdc_conclusion',
            measuredValue: this.getValDetailInfo('voltage_fcdc', allInfoList),
            checkRes: this.getCheckDetailInfo('fcdc_conclusion', allInfoList)
          },
          {
            tag:3,
            name:'交流耐压',
            outputValue:"1500kV",
            valueUrl:'voltage_fcac',
            checkUrl:'fcac_conclusion',
            measuredValue: this.getValDetailInfo('voltage_fcac', allInfoList),
            checkRes: this.getCheckDetailInfo('fcac_conclusion', allInfoList)
          },
        ]
      },
      {
        type:'AC',
        title:"交流充电口",
        infoList:[
          {
            tag:1,
            name:'绝缘电阻',
            outputValue:"1000V",
            valueUrl:'insulation_resist',
            checkUrl:'ir_conclusion',
            measuredValue: this.getValDetailInfo('insulation_resist', allInfoList),
            checkRes: this.getCheckDetailInfo('ir_conclusion', allInfoList)
          },
          {
            tag:2,
            name:'直流耐压',
            outputValue:"2100kV",
            valueUrl:'voltage_dc',
            checkUrl:'dc_conclusion',
            measuredValue: this.getValDetailInfo('voltage_dc', allInfoList),
            checkRes: this.getCheckDetailInfo('dc_conclusion', allInfoList)
          },
          {
            tag:3,
            name:'交流耐压',
            outputValue:"1500kV",
            valueUrl:'voltage_ac',
            checkUrl:'ac_conclusion',
            measuredValue: this.getValDetailInfo('voltage_ac', allInfoList),
            checkRes: this.getCheckDetailInfo('ac_conclusion', allInfoList)
          },
        ]
      },
    ]

    this.setData({
      insulationList,
      // [`instInfo.detectEndTime`]: dayjs().format("YYYY-MM-DD HH:mm:ss")
    })
  }
})